﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web;

namespace Microhard.Framework.MVCHelper
{
    public class MicroHardScriptRegister : IScriptableComponentContainer
    {
        private HttpContextBase _context;
        public MicroHardScriptRegister(HttpContextBase context)
        {
            _context = context;
        }


        #region IScriptableComponentContainer Members

        public void Register(IScriptableComponent component)
        {
            var components = _context.Items[SysConst.SCRIPT_REGISTERNAME] as Dictionary<string, IScriptableComponent>;
            if (components == null)
            {
                components = new Dictionary<string, IScriptableComponent>();
            }
            //注册页面脚本
            if (!components.ContainsKey(component.ID))
            {
                components.Add(component.ID, component);
            }
            _context.Items[SysConst.SCRIPT_REGISTERNAME] = components;
        }

        public MvcHtmlString Reander()
        {
            bool isMobile = false;
            object ismobile = _context.Items[SysConst.ISMOBILERQUEST];
            if (ismobile != null)
            {
                isMobile = bool.Parse(ismobile.ToString());
            }
            var components = _context.Items[SysConst.SCRIPT_REGISTERNAME] as Dictionary<string, IScriptableComponent>;
            if (components == null)
                return new MvcHtmlString(string.Empty);

            StringBuilder innerScript = new StringBuilder();
            StringBuilder outterScript = new StringBuilder();

            innerScript.AppendLine("<script type=\"text/javascript\">");
            if (isMobile)
            {
                innerScript.AppendLine("$( document ).on(\"pagecreate\", \"#myPage\", function() {");
            }
            else
            {
                innerScript.AppendLine("$(document).ready(function(){ ");
            }
            foreach (var m in components)
            {
                innerScript.Append(m.Value.WriteJQueryReadyInnerScript(_context));
                outterScript.Append(m.Value.WriteJQueryReadyOutterScript(_context));

            }
            innerScript.Append("}) ");
            //innerScript.AppendLine(outterScript.ToString());放入到这里面会在页面上出现函数未找到的错误，故采取下面的方式添加Grid绑定函数
            innerScript.Append("</script> ");

            StringBuilder ff = new StringBuilder();
            ff.AppendLine("<script type=\"text/javascript\">");
            ff.AppendLine(outterScript.ToString());
            ff.Append("</script>");
            innerScript.Append(ff);
            _context.Items[SysConst.SCRIPT_REGISTERNAME] = null;
            return new MvcHtmlString(innerScript.ToString());
        }
        #endregion

    }
}
